/**
* @program: Go
*
* @description:网站路由文件
*
* @author: Mr.chen
*
* @create: 2020-08-20 10:37
**/
package router

import (
	"ydd-im/config"
	"ydd-im/service/api/handler/globle"
	"ydd-im/service/api/handler/testsign"
	"ydd-im/service/api/handler/ws/group"
	"ydd-im/service/api/handler/ws/login"
	"ydd-im/service/api/handler/ws/message"
	"ydd-im/service/api/handler/ws/sendtogroup"
	"ydd-im/service/api/handler/ws/sendtouser"
	"ydd-im/service/api/handler/ws/user"
	"ydd-im/service/api/handler/ws/wsconn"
	"ydd-im/service/api/handler/ws/wsgroup"
	"ydd-im/service/api/middleware/ginprometheus"
	"ydd-im/service/api/middleware/jaeger"
	"ydd-im/service/api/services/wsservice/client"
	//"fmt"

	"github.com/gin-contrib/gzip"
	"github.com/gin-gonic/gin"
	"ydd-im/service/api/middleware/checktoken"
	//"ydd-im/service/api/handler/ws/wsconn"
	"ydd-im/service/api/middleware/cors/jsonp"
	"ydd-im/service/api/middleware/limiter"
	"ydd-im/util/response"
	//"ydd-im/service/api/middleware/exception"
	"ydd-im/service/api/middleware/sign/md5"
	"ydd-im/util/logger"
	//"ydd-im/service/api/services/wsservice/server"
	//"time"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)


func Register() *gin.Engine {
	router := gin.New()
	if !config.GetService().DebugMode {
		gin.SetMode(gin.ReleaseMode)
	}
	router.Use(logger.GinLogger(), logger.GinRecovery(true))
	router.Use(gin.ErrorLogger())
	// 采样必须放在Gzip之前，否则得出的采样是压缩包
	gp := ginprometheus.New(router)
	router.Use(gp.Middleware())
	// metrics采样
	router.GET("/metrics", gin.WrapH(promhttp.Handler()))
	//各种中间件
	router.Use(gzip.Gzip(gzip.DefaultCompression))
	//router.Use(gin.Recovery())
	router.Use(CorsMiddleware())// 解决跨域
	// 发生错误发送信息给管理员
	//router.Use(exception.SetUp())
	// 将日记保存在日记文件中

	initWsRouter(router)
	initCommonRouter(router)

	//router.Use(middleware.EnableCors([]string{"127.0.0.1:8181","localhost:8181","106.55.162.107:8181","106.55.162.107:80","xander.1024.company:80"}))

	//404
	router.NoRoute(func(c *gin.Context) {
		response.ResponseJsonFail(c,response.Response{
			Code:    response.ErrorCode,
			Message: "请输入正确的url",
		})
	})
	return router
}
// 初始化普通的路由-上传
func initCommonRouter(router *gin.Engine)  {
	router.GET("/ping", globle.Ping)
	//第2种路由组使用方式
	apiGroup := router.Group("/api")
	apiGroup.Use(sign_md5.SetUp(),limiter.SetUp(10),jsonp.SetUp()) //使用中间件
	{
		apiGroup.GET("/testsign", testsign.Sign)
	}
	router.GET("/version", globle.Version)
	// 首页接口
	//router.Use(sign_md5.SetUp(),limiter.SetUp(100000)).GET("/api/shoppage/index", handler.DoPageIndexHandler)

	//ab.exe -n 2000 -c 100 "http://127.0.0.1:7001/api/shoppage/index?pageid=1&wxappid=1002&debug=0&ak=ydd-im&sn=82f4c7ce2877d835a85dc3550e76bf18&ts=1603351155"
	////静态文件
	//router.StaticFS("/static", http.Dir("../../static"))
	//router.StaticFS("/mnt", http.Dir("./mnt"))
	//router.StaticFS("/.well-known", http.Dir("./.well-known"))
	//router.StaticFile("/favicon.ico", "../../static/logo.png")
	//router.POST("/attach/upload", globle.Upload)

}
// 初始化ws服务器接口
func initWsRouter(r *gin.Engine) {
	loginHandler := &login.Controller{}
	userHandler := &user.Controller{}
	sendtouserHandler := &sendtouser.Controller{}
	wsgroupHandler := &wsgroup.Controller{}
	messageHandler := &message.Controller{}
	sendtogroupHandler := &sendtogroup.Controller{}
	groupHandler := &group.Controller{}
	apiGroup := r.Group("/api")
	apiGroup.Use(sign_md5.SetUp(),limiter.SetUp(10),jsonp.SetUp()) //使用中间件
	apiGroup.Use(jaeger.SetUp())

	{
		apiGroup.POST("ws/register", loginHandler.Register) // 注册
		apiGroup.POST("ws/login", loginHandler.Login) // 登录
		apiGroup.POST("ws/get_online_list",userHandler.GetOnlineList) // 获取在线用户
		apiGroup.Use(checktoken.SetUp()).POST("ws/sendtouser",sendtouserHandler.SendtoUser) // 发送消息给单个用户
		apiGroup.Use(checktoken.SetUp()).POST("ws/sendtousers",sendtouserHandler.SendtoUsers) // 发送消息给多个用户
		apiGroup.Use(checktoken.SetUp()).POST("ws/bindusertogroup",wsgroupHandler.Bindusertogroup) // 发送消息给多个用户
		apiGroup.Use(checktoken.SetUp()).POST("ws/getAllUserList",userHandler.GetAllUserList) // 获取所有用户
		apiGroup.Use(checktoken.SetUp()).POST("ws/getAllGroupList",wsgroupHandler.GetAllGroupList) // 获取所有群
		apiGroup.Use(checktoken.SetUp()).POST("ws/getMessageHistoryLog",messageHandler.GetMessageHistoryLog) // 获取所有用户
		apiGroup.Use(checktoken.SetUp()).POST("ws/getAllJoinGroupList",wsgroupHandler.GetAllJoinGroupList) // 获取用户所属群
		apiGroup.Use(checktoken.SetUp()).POST("ws/sendtogroup",sendtogroupHandler.SendtoGroup) // 发送消息给单个群
		apiGroup.Use(checktoken.SetUp()).POST("ws/sendtogroups",sendtogroupHandler.SendtoGroups) // 发送消息给多个群
		apiGroup.Use(checktoken.SetUp()).POST("ws/creategroup",groupHandler.Creategroup) // 创建群
		apiGroup.Use(checktoken.SetUp()).POST("ws/joingroup",groupHandler.Joingroup) // 创建群
	}
	// 开始websocket服务
	// 连接ws
	websocketHandler := &wsconn.Controller{}
	r.GET("/ws", websocketHandler.Conn)
	r.POST("/ws", websocketHandler.Conn)
	go client.Manager.Start() // 监听客户端上线下线
	go client.WriteMessage() // 监听并发送给客户端信息，当不存在的客户端自动断开
	//启动一个定时器用来发送心跳,防止websocket长时间不连接断开
	client.PingTimer()
}
// 初始化用户路由
func initUserRouter(r *gin.Engine) {

}
// 初始化聊天页面的路由
func initChatRouter(r *gin.Engine) {

}
// 中间件-跨域请求r.Use(CorsMiddleware())
func CorsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		var openCorsFlag = true
		if openCorsFlag {

			c.Header("Access-Control-Allow-Origin", "*")
			//c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
			c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,ts,appkey,sign,token")
			c.Header("Access-Control-Allow-Methods", "GET, OPTIONS, POST, PUT, DELETE")
			//c.Set("content-type", "application/json")
			c.Set("content-type", "application/x-www-form-urlencoded")

		}
		if method == "OPTIONS" {
			response.ResponseJsonOk(c,response.Response{
				Code:    response.SuccessCode,
				Message: "pong",
			})
			c.Abort()
		}
		c.Next()
	}
}
